<template>
  <div class="product">
    <Header title="商品"></Header>

    <!-- 轮播图 -->
    <SwiperImage
      :loading="visibleStatus.skeleton.swiper"
      :images="currentSkuInfo.skuInfo.skuImageList"
    />

    <!-- spu基本信息 -->
    <SpuTitle :skuInfo="currentSkuInfo.skuInfo" />

    <!-- 规格和地址选择 -->
    <SpuMenu
      :currentSkuInfo="currentSkuInfo"
      :spuInfo="spuInfo"
      :deliveryAddress="deliveryAddress"
      @openSkuDialog="visibleStatus.saleAttrSelectDialog = true"
      @openAddressDialog="visibleStatus.addressSelectDialog = true"
    />

    <!-- 规格选择页面 -->
    <nut-action-sheet v-model:visible="visibleStatus.saleAttrSelectDialog">
      <SaleAttrSelect
        :currentSkuInfo="currentSkuInfo"
        :spuInfo="spuInfo"
        @change="handleSkuAttrChange"
        @close="visibleStatus.saleAttrSelectDialog = false"
      />
    </nut-action-sheet>

    <!-- 地址选择页面 -->
    <nut-address
      v-model:visible="visibleStatus.addressSelectDialog"
      type="exist"
      :exist-address="deliveryAddress.list"
      :is-show-custom-address="false"
      @selected="handleSelectedAddress"
      exist-address-title="配送至"
    ></nut-address>

    <!-- 商品评论 -->
    <SpuComment />

    <!-- 商品规格参数展示 -->
    <SpuAttr :groupAttrs="spuInfo.groupAttrs" />

    <!-- 商品详情展示 -->
    <SpuDesc :images="spuInfo.descs" />

    <!-- 购买按钮 -->
    <SpuBottom
      :disabled="disabledStatus.buy"
      @buy="jumpToConfirmOrder"
      @addCart="addCart"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from "vue";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

import SwiperImage from "./components/SwiperImage.vue";
import SpuTitle from "./components/SpuTitle.vue";
import SpuMenu from "./components/SpuMenu.vue";
import SaleAttrSelect from "./components/SaleAttrSelect.vue";
import SpuAttr from "./components/SpuAttr.vue";
import SpuComment from "./components/SpuComment.vue";
import SpuDesc from "./components/SpuDesc.vue";
import SpuBottom from "./components/SpuBottom.vue";

// 可见状态管理
const visibleStatus = reactive({
  saleAttrSelectDialog: false,
  addressSelectDialog: false,
  skeleton: {
    swiper: true,
  },
});

// 按钮不可用状态管理
const disabledStatus = reactive({
  buy: false,
});

// 商品信息
const spuInfo = reactive({
  // 标题
  title: "",
  // 图片列表
  images: [],
  // 详情
  desc: "",
  // 规格参数
  groupAttrs: [],
  // sku属性
  saleAttrs: [],
  hasSaleAttrs: false,
});

// 选中的sku信息
const currentSkuInfo = reactive({
  // sku基本信息
  skuInfo: {},
  // 选中的sku属性值列表
  attrValueList: [],
  // 选中的sku属性值编号列表
  attrOptionSnList: [],
});

// 初始化选中的sku信息
const initCurrentSkuInfo = () => {
  if (spuInfo.hasSaleAttrs) {
    initPathMap();
    initFirstSelectedSkuInfo();
    refreshSkuInfo();
  } else {
    currentSkuInfo.skuInfo = spuInfo.skuInfos[0];
  }
};

// 初始化可用路径map
const pathMap = reactive({});
const initPathMap = () => {
  spuInfo.skuInfos.forEach((skuInfo) => {
    if (skuInfo.stockNum > 0) {
      const powerResult = proxy.$arrayUtils.powerSet(skuInfo.attrOptionSnList);
      powerResult.forEach((item) => {
        if (item.length > 0) {
          const joinItem = item.join("-");
          if (pathMap[joinItem]) {
            pathMap[joinItem].push(skuInfo.id);
          } else {
            pathMap[joinItem] = [skuInfo.id];
          }
        }
      });
    }
  });
};

// 初始化首次选中的sku组合
const initFirstSelectedSkuInfo = () => {
  var skuId = route.query.skuId;
  spuInfo.skuInfos.forEach((skuInfo) => {
    if (skuInfo.id == skuId) {
      currentSkuInfo.attrOptionSnList = skuInfo.attrOptionSnList;
    }
  });

  // const pathMapEntryList = Object.entries(pathMap);
  // for (var i in pathMapEntryList) {
  //   var attrOptionSnList = pathMapEntryList[i][0].split("-");
  //   if (attrOptionSnList.length == spuInfo.saleAttrs.length) {
  //     currentSkuInfo.attrOptionSnList = attrOptionSnList;
  //     break;
  //   }
  // }
};

// 选中sku属性事件
const handleSkuAttrChange = (attrValue, skuIndex) => {
  // 禁用不可点击
  if (attrValue.disabled) {
    return;
  }
  // 设置选中和不选中状态
  if (currentSkuInfo.attrOptionSnList[skuIndex] == attrValue.attrOptionSn) {
    currentSkuInfo.attrOptionSnList[skuIndex] = undefined;
  } else {
    currentSkuInfo.attrOptionSnList[skuIndex] = attrValue.attrOptionSn;
  }
  refreshSkuInfo();
};

// 设置选中的sku基本信息和sku属性值列表）
const refreshSkuInfo = () => {
  updateDisabledStatus();
  var hasFoundSku = false;

  spuInfo.skuInfos.forEach((skuInfo) => {
    if (
      proxy.$arrayUtils.isEquals(
        skuInfo.attrOptionSnList,
        currentSkuInfo.attrOptionSnList
      )
    ) {
      hasFoundSku = true;
      currentSkuInfo.skuInfo = skuInfo;
    }
  });

  // 如果没有完整的sku组合
  if (!hasFoundSku) {
    disabledStatus.buy = true;
    currentSkuInfo.skuInfo = {
      title: spuInfo.title,
      price: 0,
    };
  } else {
    disabledStatus.buy = false;
  }

  // 设置选中的sku属性值列表
  currentSkuInfo.attrValueList = [];
  spuInfo.saleAttrs.forEach((skuAttr) => {
    skuAttr.optionList.forEach((skuAttrValue) => {
      if (
        currentSkuInfo.attrOptionSnList.indexOf(skuAttrValue.attrOptionSn) != -1
      ) {
        currentSkuInfo.attrValueList.push(skuAttrValue.attrValue);
      }
    });
  });
};

// 更新disabled状态
const updateDisabledStatus = () => {
  spuInfo.saleAttrs.forEach((skuAttr, skuAttrIndex) => {
    const currentOptionSnList = JSON.parse(
      JSON.stringify(currentSkuInfo.attrOptionSnList)
    );
    skuAttr.optionList.forEach((skuAttrValue) => {
      currentOptionSnList[skuAttrIndex] = skuAttrValue.attrOptionSn;
      if (pathMap[currentOptionSnList.join("-")]) {
        skuAttrValue.disabled = false;
      } else {
        skuAttrValue.disabled = true;
      }
    });
  });
};

// 收货地址列表
const deliveryAddress = reactive({
  selectedTitle: "选择配送地址",
  selectedAddress: {},
  list: [],
});
// 选中收货地址事件
const handleSelectedAddress = (prevSelected, nowSelected, arr) => {
  deliveryAddress.selectedAddress = nowSelected;
  deliveryAddress.selectedTitle =
    nowSelected.name +
    "  " +
    nowSelected.phone +
    "  " +
    nowSelected.fullAddress;
};

// 商品详情
const remoteSpuInfo = () => {
  proxy.$productApi.spu
    .info(route.query.spuId)
    .then((res) => {
      Object.assign(spuInfo, res.data);
      visibleStatus.skeleton.swiper = false;
      initCurrentSkuInfo();
    })
    .catch((error) => {});
};

// 收货地址
const remoteAddressList = () => {
  proxy.$memberApi.address.list(proxy.$userUtils.getUserId()).then((res) => {
    res.data.forEach((item) => {
      item.countyName = item.countryName;
      item.townName = "";
      if (item.defaultAddressFlag) {
        handleSelectedAddress(null, item, null);
        item.selectedAddress = true;
      } else {
        item.selectedAddress = false;
      }
    });
    deliveryAddress.list = res.data;
  });
};

// 添加购物车
const addCart = () => {
  proxy.$cartApi.cart
    .addCart(proxy.$userUtils.getUserId(), currentSkuInfo.skuInfo.id, 1)
    .then((res) => {
      proxy.$cartUtils.refreshCartList();
      router.push("/cart");
    });
};

// 立即购买
const jumpToConfirmOrder = () => {
  var skuQuantityList = [
    {
      skuId: currentSkuInfo.skuInfo.id,
      quantity: 1,
    },
  ];
  // 库存检查
  proxy.$orderApi.order.stockCheck(skuQuantityList).then((res) => {
    if (res.data.length == 0) {
      router.push({
        path: "/order/confirm",
        state: {
          cartMode: false,
          addressId: deliveryAddress.selectedAddress.id,
          skuQuantityList: skuQuantityList,
        },
      });
    } else {
      proxy.$showToast.fail("当前商品库存不足");
    }
  });
};

// 页面挂载
onMounted(() => {
  remoteSpuInfo();
  proxy.$userUtils.isLogin().then((res) => {
    if (res.data) {
      remoteAddressList();
    }
  });
});
</script>

<style lang="less" scoped>
.product {
  margin-bottom: 80px;
  :deep(.nut-address__header__title) {
    font-size: 14px;
  }
  :deep(.nut-address__header) {
    height: 50px;
  }
  :deep(.nut-address__exist) {
    margin-top: 0px;
    .nut-address__exist-group {
      height: auto;
      padding: 0px 20px 20px 20px;
    }
  }
  :deep(.nut-address__exist-item-info) {
    .nut-address__exist-item-info-name {
      margin-bottom: 5px;
    }
    .nut-address__exist-item-info-phone {
      margin-bottom: 5px;
    }
  }
}
</style>